<template>
  <div class="advanced-search-form">
    <h3 class="search-form-title">高级搜索</h3>
    <el-form :model="searchForm" label-width="100px" size="default">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="关键词">
            <el-input 
              v-model="searchForm.keyword" 
              placeholder="输入搜索关键词"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签">
            <el-select
              v-model="searchForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入标签"
              style="width: 100%"
            >
              <el-option
                v-for="tag in hotTags"
                :key="tag"
                :label="tag"
                :value="tag"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发布日期">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户">
            <el-select
              v-model="searchForm.userId"
              filterable
              remote
              reserve-keyword
              placeholder="搜索问题作者"
              :remote-method="searchUsers"
              :loading="loading"
              style="width: 100%"
            >
              <el-option
                v-for="user in userOptions"
                :key="user.id"
                :label="user.nickname || user.username"
                :value="user.id"
              >
                <div class="user-option">
                  <el-avatar :size="24" :src="user.avatar"></el-avatar>
                  <span>{{ user.nickname || user.username }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最小浏览数">
            <el-input-number 
              v-model="searchForm.minViews" 
              :min="0" 
              placeholder="最小浏览数"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最小回答数">
            <el-input-number 
              v-model="searchForm.minAnswers" 
              :min="0" 
              placeholder="最小回答数"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="排序方式">
        <el-radio-group v-model="searchForm.sort">
          <el-radio :label="1">相关度</el-radio>
          <el-radio :label="2">最新</el-radio>
          <el-radio :label="3">最热</el-radio>
          <el-radio :label="4">最多回答</el-radio>
          <el-radio :label="5">最多点赞</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item class="form-actions">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="text" @click="$emit('close')">关闭高级搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { searchUsers as fetchUsers } from '../api/search';

// 定义组件属性
const props = defineProps({
  // 初始搜索关键词
  keyword: {
    type: String,
    default: ''
  },
  // 初始搜索表单值
  initialValues: {
    type: Object,
    default: () => ({})
  }
});

// 定义组件事件
const emit = defineEmits(['search', 'close']);

// 搜索表单数据
const searchForm = ref({
  keyword: props.keyword || '',
  tags: [],
  dateRange: [],
  userId: null,
  minViews: undefined,
  minAnswers: undefined,
  sort: 1,
  ...props.initialValues
});

// 热门标签示例
const hotTags = ref([
  'javascript', 'java', 'python', 'vue', 'react', 
  'spring', '前端', '后端', '数据库', '算法'
]);

// 用户搜索数据
const loading = ref(false);
const userOptions = ref([]);

// 监听初始关键词变化
watch(() => props.keyword, (newValue) => {
  searchForm.value.keyword = newValue || '';
});

// 监听初始表单值变化
watch(() => props.initialValues, (newValues) => {
  if (newValues) {
    // 合并表单值，保留当前已设置的值
    Object.keys(newValues).forEach(key => {
      if (newValues[key] !== undefined && newValues[key] !== null) {
        searchForm.value[key] = newValues[key];
      }
    });
  }
}, { deep: true });

// 搜索用户方法
const searchUsers = async (query) => {
  if (query.length < 1) {
    userOptions.value = [];
    return;
  }
  
  loading.value = true;
  try {
    const response = await fetchUsers({
      keyword: query,
      current: 1,
      size: 10
    });
    
    if (response && response.code === 200 && response.data) {
      userOptions.value = response.data.records || [];
    } else {
      userOptions.value = [];
    }
  } catch (error) {
    console.error('搜索用户失败:', error);
    userOptions.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理搜索按钮点击
const handleSearch = () => {
  if (!searchForm.value.keyword && !searchForm.value.tags.length) {
    ElMessage.warning('请至少输入关键词或选择标签');
    return;
  }
  
  // 构建搜索参数
  const searchParams = {
    keyword: searchForm.value.keyword,
    tags: searchForm.value.tags.join(','),
    userId: searchForm.value.userId,
    startDate: searchForm.value.dateRange && searchForm.value.dateRange[0],
    endDate: searchForm.value.dateRange && searchForm.value.dateRange[1],
    minViews: searchForm.value.minViews,
    minAnswers: searchForm.value.minAnswers,
    sort: searchForm.value.sort
  };
  
  // 过滤掉空值
  Object.keys(searchParams).forEach(key => {
    if (searchParams[key] === undefined || searchParams[key] === null || searchParams[key] === '') {
      delete searchParams[key];
    }
  });
  
  // 触发搜索事件
  emit('search', searchParams);
};

// 重置表单
const handleReset = () => {
  searchForm.value = {
    keyword: props.keyword || '', // 保留关键词
    tags: [],
    dateRange: [],
    userId: null,
    minViews: undefined,
    minAnswers: undefined,
    sort: 1
  };
};
</script>

<style scoped>
.advanced-search-form {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.form-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}

.user-option {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style> 